﻿using System.Collections.ObjectModel;
using System.IO;
using System.Reflection;
using System.Windows;
using System.Windows.Threading;

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

using TimeSpan.Services;
using TimeSpan.Views;

namespace TimeSpan;

public partial class App : Application {

    private static readonly IHost _host = Host
        .CreateDefaultBuilder()
        .ConfigureAppConfiguration(c => c
            .SetBasePath(Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly()!.Location)!))
            .SetConfigBasePath(Path.Combine(Environment.GetFolderPath( Environment.SpecialFolder.LocalApplicationData), "TimeSpan"))
        )
        .ConfigureServices((context, services) => {
            services.AddHostedService<ApplicationHostService>();

            services.AddJsonConfig<SpanTasksConfig>(nameof(SpanTasksConfig));
            services.AddJsonConfig<NotesConfig>(nameof(NotesConfig));
            services.AddJsonConfig<TaskRecordsConfig>(nameof(TaskRecordsConfig));

            services.AddSingleton<INavigationService, NavigationService>();

            services.AddSingleton<WorkflowService>();
            services.AddSingleton<IDialogService, DialogService>();
            services.AddSingleton<IMessageService, MessageService>();

            services.AddAllViews();
        }).Build();

    public static T GetService<T>() where T : class {
        return _host.Services.GetRequiredService<T>();
    }

    private async void OnStartup(object sender, StartupEventArgs e) {
        await _host.StartAsync();
        ShutdownMode = ShutdownMode.OnExplicitShutdown;
    }

    private async void OnExit(object sender, ExitEventArgs e) {
        await _host.StopAsync();
        _host.Dispose();
    }

    private async void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e) {
        e.Handled = true;
        await GetService<IMessageService>().MessageAsync(e.Exception.Message);
    }

}